<?php
/**
 * Created by PhpStorm.
 * User: xiaofang
 * Date: 2020/12/12
 * Time: 11:14
 */

namespace app\api\controller;


use app\admin\model\Agateway;
use app\admin\model\NydDev;
use function PHPSTORM_META\type;
use think\facade\Cache;
use think\Controller;
use think\Db;
use think\Exception;

class Awork extends Controller
{

    /**
     *所有设备下线
     */
    public function close_all()
    {
        $ndev = new NydDev();
        $ndev->offline();
        return json(ret_com());
    }

    /**
     * 临时数据
     */
    public function new_ls_data()
    {
        $insert_data = [];
        $insert_data['time'] = date("Y-m-d H:i:s", input("time"));
        $insert_data['data'] = input("data");

        //获取时间对比
        $ndev = new NydDev();
        $ls_time = $ndev->ls_time(input("time"));

        //10秒添加数据
        if(input("time") > ($ls_time + 10000)){

            \cache('ls_time',input("time"));
            $agw = new Agateway();
            $agw->in_ls_data($insert_data);
        }
        return json(ret_com());
    }

    /**
     * 设备状态数据
     */
    public function dev_msg()
    {
        $msg_data = input("data");
        $msg_data = json_decode($msg_data,true);

        //之前缓存的设备状态数据
        $mdev = new NydDev();
        $cache_dev_status = $mdev->devStatus($msg_data['gateway_id']);

        //过滤一个数组 降维度
        $filter = [];
        foreach ($msg_data['data'] as $k => $v)
        {
            $filter[$v['mac_id']] = $v['is_open'];
        }

        //设置设备状态
        foreach ($cache_dev_status as $index => $item)
        {
            if($item != $filter[$index]){
                $cache_dev_status[$index] = $filter[$index];
                $req_str = "?is_open=".$filter[$index]."&dev_mac=".$index."&gateway_id=".$msg_data['gateway_id'];
                https_request("http://smartdp.com" . "/api/adapeng/dev_status" . $req_str);
            }
        }

        //重新设置缓存
        $mdev->setDevStatus("dev".$msg_data['gateway_id'],$cache_dev_status);
        return json(ret_com());
    }
}